package com.zys.el.time.controller;

import com.zys.el.time.common.ResultCode;
import com.zys.el.time.entity.AbsorbedDeal;
import com.zys.el.time.entity.Deal;
import com.zys.el.time.ga.Schedule;
import com.zys.el.time.ga.Task;
import com.zys.el.time.ga.TaskPlan;
import com.zys.el.time.mapper.AbsorbedDealMapper;
import com.zys.el.time.service.impl.AbsorbedDealService;
import com.zys.el.time.service.impl.DealService;
import com.zys.el.time.utils.TimeUtil;
import com.zys.el.time.vojo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/deal")
@Slf4j
@CrossOrigin
@Api(tags = "待办接口")
public class DealController {
    @Resource
    private DealService dealServer;
    @Resource
    private AbsorbedDealService absorbedDealService;

//    @GetMapping("list_feign")
//    public String


    @GetMapping("/get/{id}")
    public Deal getDealById(@PathVariable("id") String id) {
        return dealServer.getById(id);
    }


    @GetMapping("/list")
    @ApiOperation("查询当前用户的待办列表")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true)
    public Result<List<Deal>> list(@RequestParam("userId") String userId) {
        log.debug(userId);
        List<Deal> dealList = dealServer.getDealList(userId);
        AbsorbedDealMapper baseMapper = absorbedDealService.getBaseMapper();
        dealList.forEach(deal -> {
            List<AbsorbedDeal> absorbedDealList = baseMapper.getListByDealId(Long.valueOf(userId), deal.getDealId());
            if (absorbedDealList.size() > 0) {
                ArrayList<String> strings = new ArrayList<>();

                absorbedDealList.forEach(absorbed -> strings.add(absorbed.getAbsorbedDuration()));
                deal.setAbsorbedDuration(TimeUtil.handleTimeBackMin(strings));
                deal.setAbsorbedTimes(absorbedDealList.size());
            } else {
                deal.setAbsorbedDuration("0");
                deal.setAbsorbedTimes(0);
            }
        });
//        log.debug(dealList.toString());
        return Result.ok(dealList);
    }

    @PostMapping("/add")
    @ApiOperation("添加待办")
    public Result add(@RequestBody Deal deal) {
        log.info(deal.toString());
        if (deal.getSubTitle().equals("正向计时")) {
            deal.setTime(-1);
        }
        // 查询是否存在或者已被删除了
        Deal d = dealServer.getBaseMapper().getByDealName(deal.getUserId(), deal.getTitle());

        boolean b = false;
        if (d == null) {
            b = dealServer.save(deal);
        } else {
            deal.setDealId(d.getDealId());
            b = dealServer.getBaseMapper().reviveDeal(deal);
        }

        return getResult(b, "添加成功", "添加失败");
    }

    @PostMapping("/funnel")
    @ApiOperation("专注计时记录添加")
    public Result funnelAdd(@RequestBody AbsorbedDeal absorbedDeal) {
        log.debug(absorbedDeal.toString());
        String absorbedDuration = absorbedDeal.getAbsorbedDuration();
        boolean b = false;
        if (!absorbedDuration.contains("NaN") && !absorbedDuration.contains("undefined")) {
            b = absorbedDealService.save(absorbedDeal);
        }
        return getResult(b, "保存成功！", "保存失败");
    }

    @DeleteMapping("/del/{timeId}")
    @ApiOperation("删除待办")
    @ApiImplicitParam(name = "timeId", value = "待办id", required = true)
    public Result delTimeTask(@PathVariable Long timeId) {
        log.info(String.valueOf(timeId));
        boolean b = dealServer.removeById(timeId);
        return getResult(b, "删除成功", "删除失败");
    }

    @PostMapping("/modify")
    @ApiOperation("修改待办")
    public Result update(@RequestBody Deal deal) {
        log.info(deal.toString());
        if (deal.getSubTitle().equals("正向计时")) {
            deal.setTime(-1);
        }
        boolean b = dealServer.updateById(deal);

        return getResult(b, "修改成功", "修改失败");
    }

    @PostMapping("/plan")
    @ApiOperation("安排日程")
    public Result getPlan(@RequestBody List<Task> tasks) {
        try {
            List<List<Schedule>> plans = TaskPlan.doPlan(tasks, false);
            return Result.ok(plans);
        } catch (Exception e) {
            return Result.fail("失败, 请重试！");
        }
    }


    private Result getResult(boolean b, String successMsg, String errorMsg) {
        if (b) {
            return new Result(ResultCode.SUCCESS, successMsg);
        } else {
            return new Result(ResultCode.ERROR, errorMsg);
        }
    }


}
